package pl.edu.agh.agents.gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import com.mxgraph.model.mxCell;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;

public class AgentMouseAdapter extends MouseAdapter {
	private GUI gui;

	public AgentMouseAdapter(GUI gui) {
		this.gui = gui;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		mxGraph graph = gui.getGraph();
		mxGraphComponent graphComponent = gui.getGraphComponent();

		double scale = graph.getView().getScale();

		int x = (int)(e.getX() / scale);
		int y = (int)(e.getY() / scale);

		mxCell cell = (mxCell)graphComponent.getCellAt(x, y);


		if (e.getButton() == MouseEvent.BUTTON1) {
			gui.highlightPath(cell);
		}

		if (!gui.getCanEdit()) {
			return;
		}

		if (graph.getSelectionCell() == null) {
			gui.setRemoveButtonEnabled(false);
		}
		else {
			gui.setRemoveButtonEnabled(true);
		}

		// right button is used for editing graph
		if (e.getButton() == MouseEvent.BUTTON3) {
			// click on nothing
			if (cell == null) {
				gui.addState(e);
			}
			else if (cell.isVertex()) {
				mxCell selectionCell = (mxCell)graph.getSelectionCell();

				// click on cell while other cell is selected
				if (selectionCell != null && selectionCell != cell) {
					gui.setGoalState(e, cell);
				}
				// click on cell
				else {
					// cellsStates
					gui.addAgent(e, cell);
				}
			}
		}

		GraphUtils.getInstance().colorStates(gui);

		graph.refresh();
	}
}
